/**
 * @作者 faner
 * @创建时间 2021/1/15 15:31
 */
package com.faner.fast.security.component;

import cn.hutool.http.HttpStatus;
import com.faner.fast.constant.CommonConstants;
import com.faner.fast.constant.enums.CodeEnum;
import com.faner.fast.util.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义返回结果：未登录或登录过期
 * 客户端异常处理 1. 可以根据 AuthenticationException 不同细化异常处理
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private final ObjectMapper objectMapper;

//    @Override
//    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Cache-Control","no-cache");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType(CommonConstants.CONTENT_TYPE);
//        response.getWriter().println(JSONUtil.parse(R.unauthorized(authException.getMessage())));
//        response.getWriter().flush();
//    }

    @Override
    @SneakyThrows
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        R<String> result = new R<>();
        result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
        if (authException != null) {
            result.setMsg(CodeEnum.FAIL_NEED_LOGIN.getMessage());
            result.setData(authException.getMessage());
        }
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
